Page({
  data: {
    months: [],
    currentIndex: 0,
    cardHeight: 0,
    scrollOffset: 0,
    startScrollTop: 0,
    today: 0,
    moodIcons: [
      { icon: 'fa-smile-o', color: 'text-yellow-400' },
      { icon: 'fa-meh-o', color: 'text-blue-400' },
      { icon: 'fa-frown-o', color: 'text-gray-400' },
      { icon: 'fa-tired', color: 'text-orange-400' },
      { icon: 'fa-angry', color: 'text-red-400' }
    ]
  },

  onLoad() {
    // 获取系统信息，计算卡片高度
    const res = wx.getSystemInfoSync();
    const cardHeight = res.windowHeight - 140; // 减去导航栏高度
    
    // 当前日期
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1; // 转1-12
    const today = now.getDate();

    // 起始月（6个月前）
    const startDate = new Date();
    startDate.setMonth(currentMonth - 1 - 6);
    const startYear = startDate.getFullYear();
    const startMonth = startDate.getMonth() + 1;

    // 生成月份数据
    const months = [];
    let year = startYear;
    let month = startMonth;

    while (true) {
      const days = this.getDaysInMonth(year, month);
      const firstDayOfWeek = this.getFirstDayOfWeek(year, month);

      const dates = [];
      // 填充月初空白（对齐星期）
      for (let i = 0; i < firstDayOfWeek; i++) {
        dates.push({ day: 0 });
      }

      // 填充当月日期
      for (let day = 1; day <= days; day++) {
        const isPastOrToday = !(
          year > currentYear || 
          (year === currentYear && month > currentMonth) ||
          (year === currentYear && month === currentMonth && day > today)
        );
        
        // 尝试从本地存储获取心情记录
        let mood = null;
        if (isPastOrToday) {
          const key = `mood_${year}_${month}_${day}`;
          const savedMood = wx.getStorageSync(key);
          if (savedMood) {
            mood = savedMood;
          } else {
            // 没有记录时随机生成一个
            mood = this.data.moodIcons[Math.floor(Math.random() * this.data.moodIcons.length)];
            wx.setStorageSync(key, mood);
          }
        }
        
        dates.push({ 
          day, 
          hasMood: isPastOrToday,
          mood: mood
        });
      }

      const isCurrentMonth = year === currentYear && month === currentMonth;
      months.push({
        year,
        month,
        dates,
        isCurrentMonth,
        monthName: this.getMonthName(month)
      });

      // 下月逻辑
      month++;
      if (month > 12) {
        month = 1;
        year++;
      }

      // 终止：到当前月的下个月
      if (year === currentYear && month > currentMonth) break;
    }

    // 找到当前月份的索引
    const currentIndex = months.findIndex(m => m.isCurrentMonth);

    this.setData({
      months,
      currentIndex,
      cardHeight,
      today,
      // 初始滚动到当前月份
      scrollOffset: -currentIndex * cardHeight
    });
  },

  // 工具函数：获取某月天数
  getDaysInMonth(year, month) {
    return new Date(year, month, 0).getDate();
  },

  // 工具函数：获取某月1号是周几（0=周日，1=周一...6=周六）
  getFirstDayOfWeek(year, month) {
    return new Date(year, month - 1, 1).getDay();
  },

  // 工具函数：获取月份名称
  getMonthName(month) {
    const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
    return monthNames[month - 1];
  },
  // 滚动事件处理
  onScroll(e) {
    // 记录滚动位置，用于判断滚动方向
    this.setData({
      startScrollTop: e.detail.scrollTop
    });
  },

  // 滚动结束事件
  onScrollEnd(e) {
    const { cardHeight, months, currentIndex } = this.data;
    const scrollTop = e.detail.scrollTop;
    
    // 计算应该显示哪个月份
    let targetIndex = Math.round(scrollTop / cardHeight);
    
    // 边界检查
    if (targetIndex < 0) targetIndex = 0;
    if (targetIndex >= months.length) targetIndex = months.length - 1;
    
    // 如果滚动到了新的月份，更新显示
    if (targetIndex !== currentIndex) {
      this.setData({
        currentIndex: targetIndex,
        scrollOffset: -targetIndex * cardHeight
      });
      
      // 滚动到目标位置
      wx.createSelectorQuery().select('.calendar-scroll').boundingClientRect(rect => {
        wx.createSelectorQuery().select(`.month-cards[data-index="${targetIndex}"]`).boundingClientRect(monthRect => {
          wx.createSelectorQuery().select('.calendar-scroll').scrollOffset(offset => {
            const scrollTo = monthRect.top - rect.top + offset.scrollTop;
            wx.createSelectorQuery().select('.calendar-scroll').scrollTo({
              scrollTop: scrollTo,
              duration: 300
            });
          }).exec();
        }).exec();
      }).exec();
    }
  },

  // 点击日期切换心情
  onDateTap(e) {
    const { year, month, day } = e.currentTarget.dataset;
    if (day === 0) return; // 空白单元格不响应
    
    const { months, currentIndex, moodIcons } = this.data;
    
    // 检查是否是过去或今天
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1;
    const today = now.getDate();
    const isPastOrToday = !(
      year > currentYear || 
      (year === currentYear && month > currentMonth) ||
      (year === currentYear && month === currentMonth && day > today)
    );
    
    if (!isPastOrToday) return;
    
    // 查找当前日期在数据中的位置
    const newMonths = [...months];
    const dateIndex = newMonths[currentIndex].dates.findIndex(d => d.day === day);
    const currentMood = newMonths[currentIndex].dates[dateIndex].mood;
    
    // 找到当前心情的索引
    let currentMoodIndex = moodIcons.findIndex(icon => icon.icon === currentMood.icon);
    
    // 切换到下一个心情（循环）
    let nextMoodIndex = (currentMoodIndex + 1) % moodIcons.length;
    const nextMood = moodIcons[nextMoodIndex];
    
    // 更新数据
    newMonths[currentIndex].dates[dateIndex].mood = nextMood;
    
    // 保存到本地存储
    const key = `mood_${year}_${month}_${day}`;
    wx.setStorageSync(key, nextMood);
    
    this.setData({
      months: newMonths
    });
  }
})
    